package com.oppodowngrader;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.VpnService;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ProxyVpnService extends VpnService {
    private static final String TAG = "ProxyVpnService";
    private static final String CHANNEL_ID = "OppoDowngraderChannel";
    private static final int NOTIFICATION_ID = 1;

    private ParcelFileDescriptor vpnInterface;
    private ExecutorService executorService;
    private ProxyServer proxyServer;
    private boolean isRunning = false;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "VPN服务正在创建");
        createNotificationChannel();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (isRunning) {
            Log.d(TAG, "VPN服务已经在运行中");
            return START_STICKY;
        }
        
        startForeground(NOTIFICATION_ID, createNotification());
        
        // 启动代理服务器
        try {
            proxyServer = new ProxyServer(this);
            proxyServer.start();
            
            // 配置VPN
            setupVpn();
            
            isRunning = true;
            Log.d(TAG, "VPN服务启动成功");
        } catch (Exception e) {
            Log.e(TAG, "启动VPN服务失败", e);
            stopSelf();
        }
        
        return START_STICKY;
    }
    
    private void setupVpn() {
        try {
            // 创建VPN接口
            Builder builder = new Builder()
                    .setSession("OPPO耳机降级助手")
                    .addAddress("10.0.0.2", 32)
                    .addRoute("0.0.0.0", 0)
                    .addDnsServer("8.8.8.8");
            
            // 排除自己的应用避免循环
            try {
                builder.addDisallowedApplication(getPackageName());
            } catch (Exception e) {
                Log.e(TAG, "无法排除自己的应用", e);
            }
            
            // 添加其他可能需要排除的应用
            // 比如可能不需要代理的系统应用等
            
            vpnInterface = builder.establish();
            if (vpnInterface == null) {
                throw new RuntimeException("无法创建VPN接口");
            }
            
            // 启动VPN处理线程
            executorService = Executors.newFixedThreadPool(2);
            executorService.submit(new VpnRunnable());
        } catch (Exception e) {
            Log.e(TAG, "设置VPN接口失败", e);
            cleanup();
            throw new RuntimeException("无法创建VPN服务", e);
        }
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "OPPO耳机降级助手",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }
    
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
        
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("OPPO耳机降级助手")
                .setContentText("降级服务正在运行中")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentIntent(pendingIntent)
                .build();
    }    
    @Override
    public void onDestroy() {
        Log.d(TAG, "VPN服务正在销毁");
        cleanup();
        super.onDestroy();
    }
    
    private void cleanup() {
        isRunning = false;
        
        if (proxyServer != null) {
            proxyServer.stop();
            proxyServer = null;
        }
        
        if (executorService != null) {
            executorService.shutdownNow();
            executorService = null;
        }
        
        if (vpnInterface != null) {
            try {
                vpnInterface.close();
                vpnInterface = null;
            } catch (IOException e) {
                Log.e(TAG, "关闭VPN接口失败", e);
            }
        }
    }
    
    private class VpnRunnable implements Runnable {
        @Override
        public void run() {
            try {
                ByteBuffer packet = ByteBuffer.allocate(32767);
                while (isRunning) {
                    // 这里实现VPN数据包处理逻辑
                    // 由于我们使用代理服务器处理HTTP/HTTPS请求，
                    // 这个VPN接口主要用于截获网络流量并通过代理重定向
                    
                    try {
                        // 读取VPN接口中的数据
                        int length = vpnInterface.read(packet);
                        if (length > 0) {
                            // 分析数据包
                            packet.flip();
                            
                            // 简化版本：只是检测是否有数据流量
                            // 实际应用中，这里需要更复杂的IP包处理
                            Log.v(TAG, "接收到VPN数据包，大小: " + length + "字节");
                            
                            // 清空缓冲区，准备下一次读取
                            packet.clear();
                        }
                    } catch (IOException e) {
                        if (isRunning) {
                            Log.e(TAG, "VPN数据读取错误", e);
                        }
                        break;
                    }
                    
                    // 简单休眠以减少CPU使用
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        if (isRunning) {
                            Log.e(TAG, "VPN线程被中断", e);
                        }
                        break;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "VPN线程运行错误", e);
            }
        }
    }
}